package org.example.dataStructure.queue;

/**
 * 队列
 */
public class MyQueue<T> {

    private Node<T> head;
    private Node<T> tail;

    private static class Node<T>{
        public Node<T> latter;//后一个元素
        public T value;//存入的数据
    }

    //初始化
    public MyQueue(){
        this.head = null;
        this.tail = null;
    }

    //添加数据
    public boolean put(T t){
        try {
            if(this.head==null){
                Node<T> tNode = new Node<>();
                tNode.value = t;
                tNode.latter = null;
                this.head = tNode;
                this.tail = tNode;
            }else{
                Node<T> tNode = new Node<>();
                tNode.value = t;
                tNode.latter = null;
                this.tail.latter = tNode;
                this.tail = tNode;
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

    //获取队内首个元素的值，不删除
    public T peek(){
        if(this.head == null) return null;
        return this.head.value;
    }

    //获取总元素个数
    public Integer size(){
        int index = 0;
        if(this.head == null){
            return index;
        }else{
            Node<T> node = this.head;
            do {
                index ++;
                node = node.latter;
            }while (node!=null);
        }
        return index;
    }

    //出队
    public T poll(){
        Node<T> node = this.head;
        if(node==null){
            return null;
        } else if (node.latter == null) {
            T value = node.value;
            this.head = null;
            this.tail =null;
            return value;
        }
        T value = node.value;
        this.head = node.latter;
        return value;
    }

}
